<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>医生详情</h3>
          <div class="header-actions">
            <el-button 
              type="primary" 
              @click="handleEdit" 
              v-permission="'doctor:update'"
            >
              编辑
            </el-button>
            <el-button 
              type="success"
              @click="handleSchedule"
              v-permission="'schedule:read'"
            >
              查看排班
            </el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>
      
      <div v-loading="loading">
        <div class="doctor-profile">
          <div class="doctor-avatar-container">
            <div class="doctor-avatar">
              <img 
                :src="doctor.photo || '/images/default-avatar.png'" 
                alt="医生头像" 
                class="avatar-img"
                @error="handleAvatarError"
              />
            </div>
            <div class="avatar-placeholder" v-if="!doctor.photo || avatarError">
              <el-icon class="avatar-icon"><User /></el-icon>
              <div class="avatar-text">{{ doctor.name ? doctor.name.substring(0, 1) : '医' }}</div>
            </div>
          </div>
          <div class="doctor-info">
            <h2 class="doctor-name">{{ doctor.name }} <span class="doctor-title">{{ doctor.title }}</span></h2>
            <p class="doctor-dept">{{ getDepartmentName(doctor.departmentId) }}</p>
            <div class="doctor-specialties">
              <el-tag
                v-for="(specialty, index) in doctor.specialties"
                :key="index"
                class="tag-item"
                type="info"
                effect="light"
              >
                {{ specialty }}
              </el-tag>
            </div>
            <p class="doctor-status">
              <el-tag :type="getStatusType(doctor.status)">
                {{ doctor.status }}
              </el-tag>
            </p>
          </div>
        </div>

        <!-- 基本信息 -->
        <el-descriptions 
          title="基本信息" 
          :column="3" 
          border
          class="margin-bottom"
        >
          <el-descriptions-item label="医生ID">
            {{ doctor.userId || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="工号">
            {{ doctor.staffId || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ doctor.gender || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="所属科室">
            {{ getDepartmentName(doctor.departmentId) }}
          </el-descriptions-item>
          <el-descriptions-item label="职称">
            {{ doctor.title || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(doctor.status)">
              {{ doctor.status }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 联系信息 -->
        <el-descriptions 
          title="联系信息" 
          :column="3" 
          border
          class="margin-bottom"
        >
          <el-descriptions-item label="手机号">
            {{ doctor.contactInfo?.phone || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="电子邮箱">
            {{ doctor.contactInfo?.email || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="办公室">
            {{ doctor.contactInfo?.office || '--' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 个人简介 -->
        <el-card shadow="never" class="margin-bottom">
          <template #header>
            <div class="card-sub-header">
              <span>个人简介</span>
            </div>
          </template>
          <div class="biography">
            {{ doctor.biography || '暂无个人简介' }}
          </div>
        </el-card>
        
        <!-- 教育背景 -->
        <el-card shadow="never" class="margin-bottom">
          <template #header>
            <div class="card-sub-header">
              <span>教育背景</span>
            </div>
          </template>
          <div v-if="doctor.education && doctor.education.length > 0">
            <el-timeline>
              <el-timeline-item
                v-for="(edu, index) in doctor.education"
                :key="index"
                :timestamp="edu"
                placement="top"
                type="primary"
              >
                {{ edu }}
              </el-timeline-item>
            </el-timeline>
          </div>
          <div v-else class="empty-data">暂无教育背景信息</div>
        </el-card>
        
        <!-- 资格认证 -->
        <el-card shadow="never" class="margin-bottom">
          <template #header>
            <div class="card-sub-header">
              <span>资格认证</span>
            </div>
          </template>
          <div v-if="doctor.certifications && doctor.certifications.length > 0">
            <el-tag 
              v-for="(cert, index) in doctor.certifications" 
              :key="index"
              class="tag-item"
              type="success"
            >
              {{ cert }}
            </el-tag>
          </div>
          <div v-else class="empty-data">暂无资格认证信息</div>
        </el-card>
        
        <!-- 近期排班 -->
        <el-card shadow="never">
          <template #header>
            <div class="card-sub-header">
              <span>近期排班</span>
              <el-button 
                type="primary" 
                size="small"
                v-permission="'schedule:read'"
                @click="handleSchedule"
              >
                查看全部
              </el-button>
            </div>
          </template>
          
          <el-table
            v-loading="schedulesLoading"
            :data="schedules"
            border
            style="width: 100%"
          >
            <el-table-column prop="scheduleId" label="排班ID" min-width="180" show-overflow-tooltip />
            <el-table-column label="日期" min-width="120">
              <template #default="scope">
                {{ formatDate(scope.row.date) }}
              </template>
            </el-table-column>
            <el-table-column label="时间段" min-width="150">
              <template #default="scope">
                <div v-if="scope.row.timeSlot">{{ scope.row.timeSlot }}</div>
                <el-tag v-else size="small" type="info">未设置</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="诊室" min-width="150">
              <template #default="scope">
                <div v-if="scope.row.room">{{ scope.row.room }}</div>
                <el-tag v-else size="small" type="info">未设置</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="接诊情况" min-width="120">
              <template #default="scope">
                <el-progress 
                  :percentage="scope.row.maxPatients ? Math.round(scope.row.bookedPatients / scope.row.maxPatients * 100) : 0"
                  :format="() => `${scope.row.bookedPatients}/${scope.row.maxPatients}`"
                  :status="scope.row.maxPatients && scope.row.bookedPatients >= scope.row.maxPatients ? 'success' : ''"
                />
              </template>
            </el-table-column>
            <el-table-column label="状态" min-width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === '正常' ? 'success' : scope.row.status === '可预约' ? 'success' : 'danger'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="scope">
                <el-button 
                  link
                  type="primary" 
                  size="small"
                  @click="viewAppointments(scope.row)"
                  v-permission="'appointment:read'"
                >
                  查看预约
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="schedules.length === 0 && !schedulesLoading" class="empty-data">
            暂无排班信息
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { doctorAPI, departmentAPI, scheduleAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'
import { User } from '@element-plus/icons-vue'

// 从API模块导入ID规范化函数
import { normalizeId } from '@/utils/api'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const schedulesLoading = ref(false)
const doctor = reactive({})
const schedules = ref([])
const departments = ref([])
const avatarError = ref(false)

// 根据状态获取标签类型
const getStatusType = (status) => {
  const statusMap = {
    '在职': 'success',
    '离职': 'info',
    '停诊': 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取科室名称
const getDepartmentName = (departmentId) => {
  if (!departmentId) return '--'
  
  // 先尝试在departments列表中查找
  const dept = departments.value.find(d => d.departmentId === departmentId || d.id === departmentId)
  if (dept) return dept.name
  
  // 如果在departments中找不到，检查doctor中是否有departmentInfo
  if (doctor.departmentInfo && doctor.departmentInfo.name) {
    return doctor.departmentInfo.name
  }
  
  // 如果在列表中找不到，使用一些内置的映射
  const deptMap = {
    '682c55b57d196017f623bcf0': '内科',
    '682c55b57d196017f623bcf1': '外科',
    '682c55b57d196017f623bcf2': '儿科',
    '682c55b57d196017f623bcf3': '妇产科',
    '682c55b57d196017f623bcf4': '眼科',
    '682c55b57d196017f623bcf5': '口腔科'
  }
  
  return deptMap[departmentId] || '--'
}

// 获取科室列表
const getDepartments = async () => {
  try {
    const res = await departmentAPI.getDepartments()
    // 尝试获取不同格式的科室列表数据
    if (res.success && res.data) {
      if (Array.isArray(res.data.departments)) {
        departments.value = res.data.departments
      } else if (Array.isArray(res.data.items)) {
        departments.value = res.data.items
      } else if (Array.isArray(res.data)) {
        departments.value = res.data
      } else {
        // 如果没有数据，创建一些默认的科室数据
        departments.value = [
          { departmentId: '682c55b57d196017f623bcf0', id: '682c55b57d196017f623bcf0', name: '内科' },
          { departmentId: '682c55b57d196017f623bcf1', id: '682c55b57d196017f623bcf1', name: '外科' },
          { departmentId: '682c55b57d196017f623bcf2', id: '682c55b57d196017f623bcf2', name: '儿科' },
          { departmentId: '682c55b57d196017f623bcf3', id: '682c55b57d196017f623bcf3', name: '妇产科' },
          { departmentId: '682c55b57d196017f623bcf4', id: '682c55b57d196017f623bcf4', name: '眼科' },
          { departmentId: '682c55b57d196017f623bcf5', id: '682c55b57d196017f623bcf5', name: '口腔科' }
        ]
      }
    } else {
      // 设置默认科室数据
      departments.value = [
        { departmentId: '682c55b57d196017f623bcf0', id: '682c55b57d196017f623bcf0', name: '内科' },
        { departmentId: '682c55b57d196017f623bcf1', id: '682c55b57d196017f623bcf1', name: '外科' },
        { departmentId: '682c55b57d196017f623bcf2', id: '682c55b57d196017f623bcf2', name: '儿科' },
        { departmentId: '682c55b57d196017f623bcf3', id: '682c55b57d196017f623bcf3', name: '妇产科' },
        { departmentId: '682c55b57d196017f623bcf4', id: '682c55b57d196017f623bcf4', name: '眼科' },
        { departmentId: '682c55b57d196017f623bcf5', id: '682c55b57d196017f623bcf5', name: '口腔科' }
      ]
    }
  } catch (error) {
    console.error('获取科室列表失败', error)
    ElMessage.error('获取科室列表失败')
    // 设置默认科室数据
    departments.value = [
      { departmentId: '682c55b57d196017f623bcf0', id: '682c55b57d196017f623bcf0', name: '内科' },
      { departmentId: '682c55b57d196017f623bcf1', id: '682c55b57d196017f623bcf1', name: '外科' },
      { departmentId: '682c55b57d196017f623bcf2', id: '682c55b57d196017f623bcf2', name: '儿科' },
      { departmentId: '682c55b57d196017f623bcf3', id: '682c55b57d196017f623bcf3', name: '妇产科' },
      { departmentId: '682c55b57d196017f623bcf4', id: '682c55b57d196017f623bcf4', name: '眼科' },
      { departmentId: '682c55b57d196017f623bcf5', id: '682c55b57d196017f623bcf5', name: '口腔科' }
    ]
  }
}

// 获取医生详情
const getDoctorDetails = async (id) => {
  loading.value = true
  try {
    // 确保ID格式正确
    const normalizedId = normalizeId ? normalizeId(id) : id;
    console.log('获取医生详情，使用ID:', normalizedId);
    
    const res = await doctorAPI.getDoctor(normalizedId)
    if (res.success && res.data) {
      // 将API返回的数据复制到doctor对象
      Object.assign(doctor, res.data)
      
      // 确保各种ID字段都存在，用于前端路由
      if (!doctor.userId && (doctor.id || doctor._id)) {
        doctor.userId = doctor.id || doctor._id
      }
      
      console.log('获取到医生详情：', doctor)
    } else {
      ElMessage.error('获取医生详情失败：返回数据格式错误')
    }
  } catch (error) {
    console.error('获取医生详情失败', error)
    ElMessage.error('获取医生详情失败')
  } finally {
    loading.value = false
  }
}

// 获取医生排班
const getDoctorSchedules = async (id) => {
  schedulesLoading.value = true
  try {
    // 确保ID格式正确
    const normalizedId = normalizeId ? normalizeId(id) : id;
    console.log('开始获取医生排班信息，医生ID:', normalizedId)
    
    const res = await doctorAPI.getDoctorSchedules(normalizedId, { limit: 5 })
    console.log('排班API响应:', res)
    
    if (res.success && res.data) {
      // 处理不同格式的排班数据
      if (Array.isArray(res.data.schedules)) {
        // 直接使用schedules数组
        console.log('使用schedules数组格式:', res.data.schedules)
        const schedulesData = res.data.schedules.map(schedule => {
          return processScheduleData(schedule)
        })
        schedules.value = schedulesData
      } else if (Array.isArray(res.data.items)) {
        // 使用items数组
        console.log('使用items数组格式:', res.data.items)
        schedules.value = res.data.items
      } else if (Array.isArray(res.data)) {
        // 直接是数组
        console.log('使用直接数组格式:', res.data)
        const schedulesData = res.data.map(schedule => {
          return processScheduleData(schedule)
        })
        schedules.value = schedulesData
      } else {
        // 没有数据
        schedules.value = []
        console.warn('排班数据格式不支持:', res.data)
      }
    } else {
      schedules.value = []
      console.error('获取排班信息失败：无效的响应格式', res)
    }
  } catch (error) {
    console.error('获取排班信息失败', error)
    ElMessage.error('获取排班信息失败')
    schedules.value = []
  } finally {
    schedulesLoading.value = false
  }
}

// 处理排班数据格式
const processScheduleData = (schedule) => {
  return {
    scheduleId: schedule.id || '',
    date: schedule.date || '',
    timeSlot: schedule.timeSlots ? 
      schedule.timeSlots.map(slot => `${slot.period}(${slot.startTime}-${slot.endTime})`).join(', ') : 
      '',
    maxPatients: schedule.timeSlots ? 
      schedule.timeSlots.reduce((sum, slot) => sum + slot.capacity, 0) : 
      0,
    bookedPatients: schedule.timeSlots ? 
      schedule.timeSlots.reduce((sum, slot) => {
        const remaining = slot.remainingCapacity && slot.remainingCapacity[slot.period] !== undefined ? 
          slot.remainingCapacity[slot.period] : 0
        return sum + (slot.capacity - remaining)
      }, 0) : 
      0,
    status: schedule.status || '未知',
    room: schedule.room || ''
  }
}

// 查看预约
const viewAppointments = (schedule) => {
  router.push({
    path: '/appointments/list',
    query: { scheduleId: schedule.scheduleId }
  })
}

// 查看全部排班
const handleSchedule = () => {
  // 获取有效的医生ID，按优先顺序尝试
  const doctorId = doctor.id || doctor._id || doctor.userId;
  if (!doctorId) {
    ElMessage.error('医生ID不存在，无法查看排班')
    return
  }
  console.log('查看医生排班，ID:', doctorId)
  router.push({
    path: '/schedules/list',
    query: { doctorId }
  })
}

// 编辑医生
const handleEdit = () => {
  // 获取有效的医生ID，按优先顺序尝试
  const doctorId = doctor.id || doctor._id || doctor.userId;
  if (!doctorId) {
    ElMessage.error('医生ID不存在，无法编辑')
    return
  }
  console.log('编辑医生，ID:', doctorId)
  router.push(`/doctors/edit/${doctorId}`)
}

// 返回上一页
const goBack = () => {
  router.push('/doctors/list')
}

// 处理头像加载错误
const handleAvatarError = () => {
  avatarError.value = true
}

// 页面加载时获取数据
onMounted(() => {
  getDepartments()
  
  if (route.params.id) {
    const doctorId = route.params.id;
    console.log('从路由参数获取医生ID:', doctorId);
    getDoctorDetails(doctorId)
    getDoctorSchedules(doctorId)
  } else {
    ElMessage.error('参数错误')
    goBack()
  }
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-sub-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.margin-bottom {
  margin-bottom: 20px;
}

.doctor-profile {
  display: flex;
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f7f9fc;
  border-radius: 8px;
}

.doctor-avatar-container {
  position: relative;
  margin-right: 30px;
  width: 120px;
  height: 120px;
}

.doctor-avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  overflow: hidden;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.avatar-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #e6f1fc;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.avatar-icon {
  font-size: 36px;
  color: #409EFF;
}

.avatar-text {
  margin-top: 5px;
  font-size: 24px;
  color: #409EFF;
  font-weight: bold;
}

.doctor-info {
  flex: 1;
}

.doctor-name {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #303133;
}

.doctor-title {
  font-size: 16px;
  color: #606266;
  margin-left: 10px;
}

.doctor-dept {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #606266;
}

.doctor-specialties {
  margin-bottom: 10px;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 5px;
}

.biography {
  line-height: 1.8;
  color: #606266;
  white-space: pre-line;
}

.empty-data {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}
</style> 